<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'
import { importDefaultModuleAll } from '@/utils'
import FileUpload from '../file-operation/FileUpload.vue'
import ImageUpload from '../file-operation/ImageUpload.vue'
import InputNumberWithRatio from '../special/InputNumberWithRatio.vue'

const baseItems = importDefaultModuleAll(
  require.context('./base-form-items', false, /\.vue$/)
)

const itemMap: {
  [key: string]: string
} = {
  /* base items */
  divider: 'RenderDivider',
  radio: 'RenderRadio',
  checkbox: 'RenderCheckbox',
  input: 'RenderInput',
  'input-number': 'RenderInputNumber',
  select: 'RenderSelect',
  switch: 'RenderSwitch',
  slider: 'RenderSlider',
  'time-picker': 'RenderTimePicker',
  'date-picker': 'RenderDatePicker',
  rate: 'RenderRate',
  'color-picker': 'RenderColorPicker',

  /* advanced items */
  'upload-file': 'FileUpload',
  'upload-image': 'ImageUpload',
  'input-number-ratio': 'InputNumberWithRatio'
}

@Component({
  name: 'RenderFormItem',
  components: { ...baseItems, FileUpload, ImageUpload, InputNumberWithRatio }
})
export default class extends Vue {
  @Prop()
  private value: any
  // form item type
  @Prop({
    type: String,
    required: true,
    validator: v => itemMap.hasOwnProperty(v)
  })
  private type!: string
  // form item props
  @Prop({ type: Object, required: false, default: () => ({}) })
  private innerProps!: object

  render (h: CreateElement) {
    const component = itemMap[this.type]

    if (this.type === 'divider') {
      return h(component, { props: this.innerProps })
    } else {
      return h('el-form-item', { attrs: this.$attrs, props: this.$attrs }, [
        h(component, {
          attrs: this.innerProps,
          props: { ...this.innerProps, value: this.value },
          on: {
            ...this.$listeners,
            input: (v: any) => {
              this.$emit('input', v)
            }
          }
        })
      ])
    }
  }
}
</script>
